<?php
namespace ImiApp\WebSocketServer\Controller;

use Imi\ConnectContext;
use Imi\Controller\WebSocketController;
use Imi\Server\Route\Annotation\WebSocket\WSRoute;
use Imi\Server\Route\Annotation\WebSocket\WSAction;
use Imi\Server\Route\Annotation\WebSocket\WSController;
use Imi\Server\Route\Annotation\WebSocket\WSMiddleware;

use Imi\Server\Route\Annotation\WebSocket\WSConfig;


use Imi\Db\Db;
use Imi\Pool\BasePool;

use ImiApp\WebSocketServer\Controller\User;

/**
 * 数据收发测试
 * @WSController
 */
class IndexController extends WebSocketController
{
    /**
     * 发送消息
     *
     * @WSAction
     * @WSRoute({"action"="he"})
     * @param 
     * @return void
     */
    public function he($data)
    {
        $clientInfo = $this->server->getSwooleServer()->getClientInfo($this->frame->getFd());
        $message = '[' . ($clientInfo['remote_ip'] ?? '') . ':' . ($clientInfo['remote_port'] ?? '') . ']: SendContent:' . $data->message;
        return [
            'success'   =>  true,
            'data'      =>  'XiaoHe22'.$message,
        ];
    }


    /**
     * 发送消息
     *
     * @WSAction
     * @WSRoute({"action"="send"})
     * @param 
     * @return void
     */
    public function send($data)
    {
        $clientInfo = $this->server->getSwooleServer()->getClientInfo($this->frame->getFd());
        $message = '[' . ($clientInfo['remote_ip'] ?? '') . ':' . ($clientInfo['remote_port'] ?? '') . ']: SendContent:' . $data->message;
        return [
            'success'   =>  true,
            'data'      =>  'XiaoHe——SEND'.$message,
        ];
    }



    /**
     * 发送消息
     *
     * @WSAction
     * @WSRoute({"action"="send2"})
     * @param 
     * @return void
     */
    public function send2($data)
    {
        
       
        // file_put_contents('duixiang.txt',json_encode($this->server->getGroup('g1')));
        // file_put_contents('duixiang.txt',json_encode($this->server->getGroups()));

        try {
            $group = isset($data->group)?$data->group:null;
        } catch (\Throwable $th) {
            //throw $th;
        }
        if(empty($group)){
            if($this->uid_decode($data->uid)>$data->re_uid){
                $group = $this->uid_decode($data->uid).'_'.$data->re_uid; 
            }else{
                $group = $data->re_uid.'_'.$this->uid_decode($data->uid); 
            }
               
        }

        $db = Db::query();
        $indata['time'] = time();
        $indata['content'] = $data->message;
        $indata['username'] = $data->username;
        $indata['send_uid'] = $this->uid_decode($data->uid);
        $indata['group'] = $group;
        $indata['re_uid'] = $data->re_uid;

        $clientInfo = $this->server->getSwooleServer()->getClientInfo($this->frame->getFd());
        $indata['ip'] = $clientInfo['remote_ip'];
        $db->table('wst_chat')->insert($indata);

        $num = 1;
        // foreach($this->server->connections as $fd) {

        //     $num++;
        // }
        // // $num = $this->server->count;
        // $Pool = new BasePool;
        // $num = $Pool->getUsed();//count($this->server->connections);
        $num = $this->server->getGroup($group)->count();
        // getpeername
        $this->server->groupCall($group, 'push', '当前在线人数'.$num.'>>>'.'>>>:'.$data->message);//ConnectContext::get('username')
        // $this->server->groupCall($group, 'push', 'XiaoHe'.'>>>:'.file_get_contents('http://i.itpk.cn/api.php?question='.$data->message));//ConnectContext::get('username')
        
        // $clientInfo = $this->server->getSwooleServer()->getClientInfo($this->frame->getFd());
        // $message = '[' . ($clientInfo['remote_ip'] ?? '') . ':' . ($clientInfo['remote_port'] ?? '') . ']: SendContent:' . $data->message;
        // return [
        //     'success'   =>  true,
        //     'data'      =>  'send2'.$message,
        // ];
    }


    /**
     * 加入系统房间
     *
     * @WSAction
     * @WSRoute({"action"="joinSysRoom"})
     * @WSConfig(parserClass=\Imi\Server\DataParser\JsonObjectParser::class)
     * @param array $data
     * @return void
     */
    public function joinSysRoom($data)
    {

        var_dump('{"action":"im.joinSysRoom"}');
        if(!isset($data['roomId'])){
            $data['roomId'] = 'com';
        }
        $group = 'im.room.' . $data['roomId'];
        $this->server->joinGroup($group, $this->frame->getFd());

        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');
        var_dump($memberSession);
        Server::sendToGroup($group, [
            'action'    =>  MessageActions::IM_RECEIVE,
            'sender'    =>  '系统消息',
            'type'      =>  MessageType::SYSTEM,
            'content'   =>  $memberSession->getMemberInfo()->username . ' 上线了',
            'time'      =>  date('Y-m-d H:i:s'),
        ]);
        return [
            'action'    =>  MessageActions::IM_JOIN_ROOM,
        ];
    }




    /**
     * 给某个用户发送消息
     *
     * @WSAction
     * @WSRoute({"action"="send_user"})
     * @param 
     * @return void
     */
    public function send_user($data)
    {   
        $re_user = new User($data->re_uid);
        $send_user = new User($this->uid_decode($data->uid));
        if(!$re_user->is_uid()){
            // $this->server->groupCall($group, 'push', '当前在线人数'.$num.'>>>'.'>>>:'.$data->message);
            return ['code'=>-1,'success'=>false,'msg'=>'没有此接收者的用户'.$data->re_uid,'date'=>date('Y-m-d H:i:s')];
        }elseif(!$send_user->is_uid()){
            return ['code'=>-1,'success'=>false,'msg'=>'没有此用户,请勿修改参数','date'=>date('Y-m-d H:i:s')];
        }

        if($this->uid_decode($data->uid)>$data->re_uid){
            $group = $this->uid_decode($data->uid).'_'.$data->re_uid; 
        }else{
            $group = $data->re_uid.'_'.$this->uid_decode($data->uid); 
        }
        //类型:1=普通消息,2=心跳,3=订单号,4=用户确认报价,5=商家同意报价,6=用户评价订单,10=语音,11=图片,12=文件
        $type = property_exists($data,'type')?$data->type:'1';
        var_dump('type'.$type);
        if($type==7){
            //消息已读
            $this->msg_status_Read($data->message);
            return null;
        }

    
        $ltd = new \ImiApp\WebSocketServer\Controller\Ltd;
        // var_dump($ltd->get_ltd($data->re_uid,$this->uid_decode($data->uid),$data->ask_id));//
        if(!$ltd->get_send_status($data->re_uid,$this->uid_decode($data->uid),$data->ask_id) && $type!='5'){
            //订单已完结  不能发送
            // $this->server->groupCall($group, 'push',json_encode(['msg'=>'订单关闭无法发送消息，请重新建立对话框',
            //                                                     'code'=>1,
            //                                                     're_uid'=>$data->re_uid,
            //                                                     'send_uid'=>$this->uid_decode($data->uid),
            //                                                     'type'=>'1',
            //                                                     'date'=>date('Y-m-d H:i:s')]));

                                                                return ['msg'=>'订单关闭无法发送消息，请重新建立对话框',
                                                                'code'=>1,
                                                                're_uid'=>$data->re_uid,
                                                                'send_uid'=>$this->uid_decode($data->uid),
                                                                'type'=>'1',
                                                                'date'=>date('Y-m-d H:i:s')];
        }else{
            $db = Db::query();
            $indata['time'] = time();
            $indata['content'] = $data->message;
            // $indata['username'] = $data->username;
            $indata['send_uid'] = $this->uid_decode($data->uid);
            $indata['group'] = $group;
            $indata['re_uid'] = $data->re_uid;
            $indata['type'] = $type;
    
            $indata['ask_id'] = isset($data->ask_id)?$data->ask_id:null;//判询价单是否存在
    
            $clientInfo = $this->server->getSwooleServer()->getClientInfo($this->frame->getFd());
            $indata['ip'] = $clientInfo['remote_ip'];
    
            
            $result = $db->table('wst_chat')->insert($indata);
            $msg_id = $result->getLastInsertId();
    
            $num = 1;
            // foreach($this->server->connections as $fd) {
    
            //     $num++;
            // }
            // // $num = $this->server->count;
            // $Pool = new BasePool;
            // $num = $Pool->getUsed();//count($this->server->connections);
            $num = $this->server->getGroup($group)->count();
            // getpeername
            $this->server->groupCall($group, 'push',json_encode(['msg'=>$data->message,
                                                                    'code'=>1,
                                                                    're_uid'=>$data->re_uid,
                                                                    'send_uid'=>$this->uid_decode($data->uid),
                                                                    'type'=>$type,
                                                                    'id'=>$msg_id,
                                                                    'date'=>date('Y-m-d H:i:s')]));//ConnectContext::get('username')
            // $this->server->groupCall($group, 'push', 'XiaoHe'.'>>>:'.file_get_contents('http://i.itpk.cn/api.php?question='.$data->message));//ConnectContext::get('username')
            
            // $clientInfo = $this->server->getSwooleServer()->getClientInfo($this->frame->getFd());
            // $message = '[' . ($clientInfo['remote_ip'] ?? '') . ':' . ($clientInfo['remote_port'] ?? '') . ']: SendContent:' . $data->message;
            
            // return [
            //     'code'  => 1,
            //     'success'   =>  true,
            //     'data'      =>  'send_ok',//消息发送成功
            //     'date'=>date('Y-m-d H:i:s')
            // ];
        }

      
    }



    /**
     * 登录(类似于创建房间)
     *
     * @WSAction
     * @WSRoute({"action"="login"})
     * @WSConfig(parserClass=\Imi\Server\DataParser\JsonObjectParser::class)
     * @param 
     * @return void
     */
    public function login($data)
    {
        \Imi\App::setDebug(true);
        // ConnectContext::set('send_uid', $this->uid_decode($data->uid));
        

        $user = new User($this->uid_decode($data->uid));
        // var_dump($user);
        // var_dump($user->is_uid());
        if($user->is_uid()){//有这个用户

            // ConnectContext::set($this->uid_decode($data->uid), $data->username);

            try {
                $group = isset($data->group)?$data->group:null;//判断组是否存在
            } catch (\Throwable $th) {
                //throw $th;
            }

            if(empty($group)){
                if($this->uid_decode($data->uid)>$data->re_uid){
                    $group = $this->uid_decode($data->uid).'_'.$data->re_uid; 
                }else{
                    $group = $data->re_uid.'_'.$this->uid_decode($data->uid); 
                }
                var_dump($group);   
            }

            
                
            $this->server->joinGroup($group, $this->frame->getFd());//加入群组

            $num = $this->server->getGroup($group)->count();//这个组里面的人数
            // $this->server->groupCall($group, 'push', json_encode(['sys_msg'=>'加入聊天','num'=>$num]));//发送消息

            // $db = Db::query();
            // $indata['time'] = time();
            // $indata['content'] = '加入聊天,在线人数'.$num;
            // // $indata['username'] = $data->username;
            // $indata['send_uid'] = $this->uid_decode($data->uid);
            // $indata['group'] = $group;
            // $indata['re_uid'] = $data->re_uid;

            // $clientInfo = $this->server->getSwooleServer()->getClientInfo($this->frame->getFd());//获取连接者的信息
            // $indata['ip'] = $clientInfo['remote_ip'];


            // $db->table('wst_chat')->insert($indata);

            // $db_user = Db::query();
            // $db_user->table('wst_user')->where('id','=',$this->uid_decode($data->uid))->update(['on_line'=>1]);
            return ['code'=>1,'success'=>true,'msg'=>'login_success','date'=>date('Y-m-d H:i:s'),'uid'=>$this->uid_decode($data->uid)];
        }else{
            return ['code'=>-1,'success'=>false,'msg'=>'没有此用户','date'=>date('Y-m-d H:i:s')];
            $this->request->getServerInstance()->getSwooleServer()->close($this->frame->getFd());
            // $this->server->close($this->frame->getFd());
        }
        
        
        
       
    }

    // /* 
    // * 是否是用户
    // */     
    // public function is_uid($uid=null)
    // {
    //     if($uid){
    //         $db = Db::query();
    //         $user = $db->table('wst_user')->where('id','=',$uid)->select()->get();
    //         // var_dump($user);
    //         if($user){
    //             return true;
    //         }else{
    //             return false;
    //         }
    //     }else{
    //         return false;
    //     }    
    // }


    public function uid_decode($uid_str)
    {   
         //非纯数字
        if(is_numeric($uid_str)){
            return $uid_str;
        }
        // $uid = base64_decode($uid_str);
        $data = json_decode(base64_decode(substr($uid_str, 2)),true);
        if($data){
            $uid = $data['uid'];
        }else{
            $uid = null;
        }
        return $uid;
    }

    /**
     * 消息已读
     *
     * @param [type] $id
     * @return void
     */
    public function msg_status_Read($id)
    {
        var_dump($id);
        $db = Db::query();
        $res = $db->table('chat')->where('id','=',$id)->update(['msg_status'=>1]);
    }

    

    // public function get_uid($uid=null)
    // {
    //     $json['code'] = -1;
    //     if(!$uid){
    //         $json['msg'] = '请传递正确参数';
            
    //     }else{
    //         $db = Db::query();
    //         $user = $db->table('wst_user')->where('id','=',$uid)->select()->get();
    //         // var_dump($user);
    //         if($user){
    //             $json['code'] = 1;
    //             $json['data'] = $user;
    //         }
    //         $json['msg'] = '此用户不存在';
    //     }
    //     return $json;
        
    // }


}